package top.hepingan.java.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.hepingan.java.common.Result;
import top.hepingan.java.entity.Gratitude;
import top.hepingan.java.mapper.GratitudeMapper;
import top.hepingan.java.utils.UserUtils;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/displaybottle")
@Slf4j
@RequiredArgsConstructor
public class DisplaybottleController {

    @Autowired
    private GratitudeMapper gratitudeMapper;

    /**
     * 展示感恩墙列表
     */
    @GetMapping("/list")
    public Result list() {
        List<Gratitude> list = gratitudeMapper.selectList(
                new LambdaQueryWrapper<Gratitude>()
                        .eq(Gratitude::getAuditStatus, 1)  // 只显示审核通过的
                        .orderByDesc(Gratitude::getCreateTime) // 按时间倒序
        );
        return Result.data(list);
    }

    /**
     * 点赞感恩墙
     */
    @PostMapping("/like/{id}")
    public Result like(@PathVariable Long id) {
        Gratitude gratitude = gratitudeMapper.selectById(id);
        if (gratitude == null) {
            return Result.error("感恩墙不存在");
        }
        // 点赞数 +1
        gratitude.setLikeCount(gratitude.getLikeCount() + 1);
        int update = gratitudeMapper.updateById(gratitude);
        if (update > 0) {
            return Result.ok("点赞成功");
        }
        return Result.error("点赞失败");
    }

    /**
     * 发布感恩墙
     */
    @PostMapping("/publish")
    public Result publish(@RequestBody Gratitude gratitude) {
        gratitude.setUserId(UserUtils.getCurrentLoginId());
        gratitude.setCreateTime(LocalDateTime.now());
        gratitude.setLikeCount(0);
        gratitude.setCommentCount(0);
        gratitude.setAuditStatus(0); // 默认待审核
        int insert = gratitudeMapper.insert(gratitude);
        if (insert > 0) {
            return Result.ok("发布成功");
        }
        return Result.error("发布失败");
    }
}
